package com.inno.subject.application.mq;

import cn.hutool.core.lang.Pair;
import com.alibaba.fastjson.JSON;
import com.inno.auth.entity.MemberDTO;
import com.inno.subject.common.enums.CorrectCountRewardEnum;
import com.inno.subject.common.enums.MemberTypeEnum;
import com.inno.subject.common.enums.YesOrNoEnum;
import com.inno.subject.common.utils.DateUtils;
import com.inno.subject.infra.basic.entity.PlannerSubjectRecords;
import com.inno.subject.infra.basic.service.PlannerSubjectRecordsService;
import com.inno.subject.infra.rpc.UserRpc;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author shenzeyang
 */
@Slf4j
@Service
@RocketMQMessageListener(topic = "calc-correct-count", consumerGroup = "subjectCalcCorrectCountGroup")
public class CalcCorrectCountListener implements RocketMQListener<MessageExt> {
    private final PlannerSubjectRecordsService recordsService;
    private final UserRpc userRpc;
    public CalcCorrectCountListener(PlannerSubjectRecordsService recordsService,UserRpc userRpc){
        this.recordsService = recordsService;
        this.userRpc = userRpc;
    }
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        Long currentUser = Long.parseLong(new String(body));
        PlannerSubjectRecords records = new PlannerSubjectRecords();
        records.setUserId(currentUser);
        records.setIsRight(YesOrNoEnum.YES.getCode());
        long rightCount = recordsService.count(records);
        // 没有达到最小奖励次数
        if (rightCount < CorrectCountRewardEnum.ONE_DAY_VIP.getCorrectCount()){
            return;
        }

        Pair<Date, MemberTypeEnum> timeAndType = CorrectCountRewardEnum.calcMemberEndTimeAndMemberType(rightCount);
        MemberDTO memberDTO = new MemberDTO();
        String memberType = timeAndType.getValue().getCode();
        memberDTO.setMemberType(memberType);
        Date endTime = timeAndType.getKey();
        memberDTO.setEndTime(endTime);
        memberDTO.setStartTime(DateUtils.getNowDate());
        memberDTO.setUserId(currentUser);
        memberDTO.setPaymentMethod("赠送");
        memberDTO.setCreateTime(DateUtils.getNowDate());
        memberDTO.setIsDeleted(YesOrNoEnum.NO.getCode());
        try {
            this.userRpc.gifts(memberDTO);
        }catch (Exception e){
            log.error("赠送会员失败，当前用户id:{} , 需赠送的会员类型:{} ，预计赠送后会员到期时间:{} , 异常信息: ",currentUser,memberType,endTime,e);
        }
    }
}
